package com.spring.demo.tx;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @version 1.0.0
 * @Date: 2022/5/31 9:38
 * @Author ZhuYouBin
 * @Description
 */
public class MoneyService2 {
    public static void main(String[] args) {
        // 1、读取配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        // 2、获取事务管理模板对象
        TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class);
        // 3、获取Jdbc模板对象
        JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);

        // 开始事务
        transactionTemplate.execute(new TransactionCallback<Object>() {
            // 在这个方法里面执行事务代码
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                String message = "执行成功";
                try {
                    // A用户减少1000元
                    String sql = "UPDATE spring.t_money SET balance = balance - 1000  WHERE id = 10001";
                    int update = jdbcTemplate.update(sql);
                    System.out.println("A用户减少1000元成功: " + update);

                    // 模拟转账过程中出现异常
//                    int i = 10 / 0;

                    // B用户增加1000元
                    sql = "UPDATE spring.t_money SET balance = balance + 1000  WHERE id = 10002";
                    update = jdbcTemplate.update(sql);
                    System.out.println("B用户减少1000元成功: " + update);
                } catch (Exception e) {
                    // 出现异常时候, 回滚事务
                    transactionStatus.setRollbackOnly();
                    message = "执行失败";
                }
                return message;
            }
        });
    }
}
